package com.qingzhuge.netty.common.handler;

import com.qingzhuge.netty.common.message.HeartBeatMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
 * @author : zero.xiao
 * @description :
 * @date :2018/9/28 0028 下午 15:18
 * @since : 1.0.0
 * @modified :
 */
public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {
	private String heartbeat;

	public HeartBeatClientHandler(String heartbeat) {
		this.heartbeat = heartbeat;
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleState state = ((IdleStateEvent) evt).state();
			if (state == IdleState.WRITER_IDLE) {
				HeartBeatMessage msg = new HeartBeatMessage();
				msg.setHeartbeat(heartbeat);
				ctx.writeAndFlush(msg);
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

}
